""" 路由配置 """

from flask import Blueprint, request, jsonify
from werkzeug.exceptions import BadRequest
from werkzeug.exceptions import Unauthorized
from app.extensions import limiter
from app.services import auth_service  # 导入整个服务模块


auth_bp = Blueprint('auth', __name__)

@auth_bp.route('/login', methods=['POST'])
@limiter.limit("10 per minute")
def login():
    """ 登录路由 (仅处理HTTP相关) """
    try:
        # 1. 验证请求格式
        if not request.is_json:
            raise BadRequest("请求必须是JSON格式")

        data = request.get_json()

        # 2. 验证数据格式 (服务层校验)
        auth_service.AuthService.validate_login_data(data)

        # 3. 执行业务逻辑 (服务层核心)
        access_token, user = auth_service.AuthService.authenticate(data['username'], data['password'])
        # 4. 返回响应
        return jsonify(access_token=access_token)

    except BadRequest as e:
        return jsonify({"error": str(e)}), 400
    except Unauthorized as e:
        return jsonify({"error": str(e)}), 401
    except Exception as e:
        # 生产环境应记录日志而非直接打印
        return jsonify({"error": "服务器内部错误"}), 500

@auth_bp.route('/register', methods=['POST'])
@limiter.limit("1 per minute")
def register():
    """ 注册 """
    try:
        # 1. 获取请求数据
        data = request.get_json()
        if not data or 'username' not in data or 'password' not in data:
            return jsonify({"error": "需要用户名和密码"}), 400

        # 2. 调用服务层核心逻辑
        user = auth_service.register_user(data['username'], data['password'])

        # 3. 返回响应
        return jsonify({
            "message": "注册成功",
            "user_id": user.id
        }), 201

    except ValueError as e:  # 捕获服务层抛出的业务异常
        return jsonify({"error": str(e)}), 409
    except Exception:
        return jsonify({"error": "服务器错误"}), 500
